即使const成员函数将修改成员的值,以下将编译.怎么会这样 ?
#include <iostream>
struct foo
{
std::string &str;
foo(std::string &other) : str(other) {}
void operator()(std::string &some) const
{
str += some;
}
};
int main()
{
std::string ext("Hello");
foo a{ ext };
std::string more(" world!");
a(more);
cout << a.str;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我刚刚发现在没有任何const_cast黑魔法的情况下修改const对象是多么容易.考虑:
#include <iostream>
class Test {
public:
Test(int v)
:m_val{ v },
m_ptr{ &m_val }
{}
int get() const { return m_val; }
void set(int v) const { *m_ptr = v; }
private:
int m_val;
int* m_ptr;
};
int main()
{
const Test t{ 10 };
std::cout << t.get() << '\n';
t.set(0);
std::cout << t.get() << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
最近版本的Clang,GCC和MSVC没有显示任何警告并产生预期输出:
10 0
这是根据现行标准定义良好的行为吗?如果它未定义什么,如果m_val是类型std::aligned_storage_t<sizeof(int), alignof(int)>和构造new"版int的呢?我相信在小缓冲区优化方面这是很常见的情况.
编辑
谢谢,看起来这只是另一种用脚射击自己的方式.令人不安的是,这似乎是:
struct Test2 { …Run Code Online (Sandbox Code Playgroud) 我发现下面的行为真的很奇怪,这只是我代码中一个奇怪错误的原因。将带有引用的对象作为常量引用传递,然后使用这些引用来更改它们引用的对象是否被认为是不好的?我知道引用没有改变,但我会假设将对象作为 const ref 传递会使它的所有成员也成为 const 吗?
struct wrapr{
int& a;
};
void mod(const wrapr& aaa){
aaa.a = 1;
}
int main() {
int b = 2;
wrapr a {b};
mod(a);
std::cout << b; // prints 1
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
奇怪的是,如果我要声明结构
struct wrapr{
const int& a;
};
Run Code Online (Sandbox Code Playgroud)
那么代码将无法编译。我猜当你通过 const 引用传递一个对象时,我有什么心理模型,它与在它的所有成员变量上加上“const”前缀相同。显然情况并非如此。