[英]What is the GCC option for disabling assignment operator optimizations
Let's start with this small example: 让我们从这个小例子开始:
#include <vector>
#include <iostream>
using namespace std;
class A {
private:
A& operator =(const A&);
};
int main(void) {
vector<A> v;
v = { A() };
return 0;
}
Compilation of this code fails with the error message error: 'A& A::operator=(const A&)' is private
. 此代码的编译失败,并显示错误消息
error: 'A& A::operator=(const A&)' is private
。 I have no idea why it needs the assignment operator so I tried to find out and changed the code to this: 我不知道为什么它需要赋值运算符,所以我试图找出并更改代码为:
#include <vector>
#include <iostream>
using namespace std;
class A {
public:
A& operator =(const A& a) { cout << "operator=" << endl; return *this; }
};
int main(void) {
vector<A> v;
v = { A() };
return 0;
}
Now the code compiles but when I execute it it does not output the debug message in the assignment operator implementation. 现在代码可以编译,但是当我执行它时,它不会在赋值运算符实现中输出调试消息。
So the compiler wants the assignment operator but doesn't use it? 因此,编译器需要赋值运算符,但不使用它吗? I guess the compiler optimizes the assignment away somehow.
我猜编译器会以某种方式优化分配。 Just like it optimizes the usage of move constructors (Which can be prevented with the option
-no-elide-constructors
). 就像它优化了移动构造函数的用法一样(可以使用
-no-elide-constructors
选项来避免这种情况)。 Is there a compiler option which can prevent assignment optimimzations? 有没有可以防止分配优化的编译器选项? Or is there a different explanation why the compiler wants to have an accessible assignment operator but doesn't use it during runtime?
还是有不同的解释,为什么编译器希望具有可访问的赋值运算符,但在运行时不使用它?
In C++03, types being stored in a container need to be CopyConstructible
and Assignable
. 在C ++ 03中,存储在容器中的类型需要为
CopyConstructible
和Assignable
。 In C++11, requirements are relaxed and applied to the operations performed on the container. 在C ++ 11中,放宽了要求并将其应用于在容器上执行的操作。
class A
needs to be CopyConstructible
and Assignable
because being stored in vector
That's why you need public operator=
class A
必须是CopyConstructible
和Assignable
因为它存储在vector
这就是为什么需要public operator=
int main(void) {
vector<A> v;
v = { A() }; // Copy Constructor
A x;
x = v[0]; // operator=
return 0;
}
I little bit late but I still want to answer your question. 我有点晚了,但我仍然想回答你的问题。
Your example shows a standard copy elision of C++. 您的示例显示了C ++的标准复制省略 。 This is also discussed in another question .
这也在另一个问题中讨论。
That is, the compiler checks the correctness of your operation . 也就是说,编译器检查操作的正确性 。 You have to call a copy constructor right after default constructor to use vector and put your class inside, but call the default constructor only in order to improve performance.
您必须在默认构造函数之后立即调用复制构造函数以使用vector并将类放入内部,但是仅为了提高性能才调用默认构造函数 。
C++ 11 solves the issue with the move constructor . C ++ 11通过move构造函数解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.