这在C ++中是安全的吗? [英] Is this safe in C++?

查看:89
本文介绍了这在C ++中是安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的课程类似于:

If I have a class that looks something like:

class Student {
public:
   // not shown
private:
  string lastName;
  string firstName;
}



定义两个Student实例并定义它们是否安全,即使我没有定义赋值运算符也是如此。我的想法是,这不是因为我要在字符串上得到一个浅表副本,这会在调用字符串对象的析构函数时引起问题。我是对的吗?



Bob



我尝试过:



我厌倦了它并使用gnu C ++编译器工作。


Is it safe to define two instances of Student and assign them even if I do not have an assignment operator defined. My thinking is that is not because I am going to get a shallow copy on the strings which will cause problems when the destructor for the string objects get called. Am I right about that?

Bob

What I have tried:

I tired it and it worked using the gnu C++ compiler.

推荐答案

会有一个为您的类隐式声明的复制赋值运算符。因为它包含非平凡成员( std :: string ),它将执行成员方式的复制分配(为每个字符串成员调用复制分配)。另请参见复制赋值运算符 - cppreference.com [ ^ ]。



这不是如果你的类有一个指向已分配内存的成员或者是具有这样的类的成员并且没有复制赋值操作符,则是安全的。



但是 std :: string 有一个复制赋值运算符,因此是安全的。
There will be a implicitly-declared copy assignment operator for your class. Because it contains non-trivial members (std::string), that will perform a member-wise copy assignment (call the copy assigment for each string member). See also Copy assignment operator - cppreference.com[^].

It would be not safe if your class has a member pointing to allocated memory or members that are classes having such and do not have a copy assignment operator.

But std::string has a copy assignment operator and it is therefore safe.


这篇关于这在C ++中是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆