小编Pio*_*ycz的帖子

有没有办法使用基于范围的for循环迭代最多N个元素?

我想知道是否有一种很好的方法可以使用基于for循环的范围和/或标准库中的算法迭代容器中的大多数N个元素(这就是重点,我知道我可以使用"旧的" "带有条件的for循环".

基本上,我正在寻找与此Python代码相对应的内容:

for i in arr[:N]:
    print(i)
Run Code Online (Sandbox Code Playgroud)

c++ boost stl c++11 c++14

40
推荐指数
7
解决办法
5220
查看次数

std :: move是否真的需要在构造函数的初始化列表中通过值传递的重成员?

最近我从cppreference中读到了一个例子.../vector/emplace_back:

struct President
{
    std::string name;
    std::string country;
    int year;

    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        std::cout << "I am being constructed.\n";
    }
Run Code Online (Sandbox Code Playgroud)

我的问题:这std::move真的需要吗?我的观点是,这p_name不是在构造函数体中使用,所以,也许,语言中有一些规则默认使用移动语义?

将std :: move初始化列表添加到每个重要成员(例如std::string,std::vector)会非常烦人.想象一下用C++ 03编写的数百个KLOC项目 - 我们是否应该添加到处std::move

这个问题:move-constructor-and-initialization-list答案说:

作为一个黄金法则,无论何时你通过右值引用来获取内容,你需要在std :: move中使用它,并且每当你通过通用引用(即用&&推导出模板化类型)时,你需要在std ::里面使用它向前

但我不确定:通过价值而不是普遍的参考?

[UPDATE]

使我的问题更清楚.构造函数参数可以被视为XValue - 我的意思是到期值?

在这个例子AFAIK我们不使用std::move:

std::string getName()
{
   std::string local = "Hello SO!";
   return local; // std::move(local) is not needed nor …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer initialization-list move-semantics c++11

34
推荐指数
3
解决办法
7321
查看次数

为什么不能简单地初始化(带括号)2D std :: array?

可能重复:
c ++为什么std :: vector和std :: array的initializer_list行为不同

我定义了简单的2D数组(3X2):

  std::array<std::array<int,3>,2> a {
    {1,2,3},
    {4,5,6}
  };
Run Code Online (Sandbox Code Playgroud)

我很惊讶这个初始化不起作用,用gcc4.5错误: too many initializers for 'std::array<std::array<int, 3u>, 2u>'

为什么我不能使用这种语法?

我找到了解决方法,一个非常有趣的额外括号,但只是想知道为什么第一个,最简单的方法是无效的?

解决方法:

  // EXTRA BRACES
  std::array<std::array<int,3>,2> a {{
    {1,2,3},
    {4,5,6}
  }};

  // EXPLICIT CASTING
  std::array<std::array<int,3>,2> a {
    std::array<int,3>{1,2,3},
    std::array<int,3>{4,5,6}
  };
Run Code Online (Sandbox Code Playgroud)

[UPDATE]

好的,感谢KerrekSB和评论,我得到了不同.所以在我的例子中似乎有太少的括号,就像在这个C例子中一样:

struct B {
  int array[3];
};
struct A {
  B array[2];
};

B b = {{1,2,3}};
A a = {{
     {{1,2,3}},
     {{4,5,6}}
}};
Run Code Online (Sandbox Code Playgroud)

c++ stl initialization c++11

31
推荐指数
1
解决办法
2万
查看次数

使用贴片新操作符时,我真的不得不担心对齐吗?

我读过这个 什么时候应该担心对齐?但我仍然不知道我是否要担心放置新运算符返回的对齐指针 - 就像在这个例子中:

class A {
public:
   long double a;
   long long b;
   A() : a(1.3), b(1234) {}
};

char buffer[64];

int main() {
   // (buffer + 1) used intentionally to have wrong alignment
   A* a = new (buffer + 1) A(); 
   a->~A();
}
Run Code Online (Sandbox Code Playgroud)

__alignof(A) == 4,(buffer + 1)是不对齐的4.但一切正常 - 这里有完整的例子:http://ideone.com/jBrk8

如果这取决于架构,那么我正在使用:linux/powerpc/g ++ 4.xx

[更新]发布此问题后,我读了这篇文章:http://virtrev.blogspot.de/2010/09/memory-alignment-theory-and-c-examples.html.也许在我的情况下唯一的缺点是性能损失,我的意思是未对齐的访问成本超过对齐?

c++ g++ powerpc memory-alignment placement-new

23
推荐指数
2
解决办法
5129
查看次数

为什么auto_ptr不支持op - >*()

auto_ptr(shared_ptr也是如此)尽量使它们尽可能透明; 也就是说,理想情况下,您不应该区分是否使用auto_ptr或指向对象的实际指针.考虑:

class MyClass
{
public:
    void foo() {  }
};

MyClass* p = new MyClass;
auto_ptr<MyClass> ap(new MyClassp);

p->foo();       // No notational difference in using real
ap->foo();      // pointers and auto_ptrs
Run Code Online (Sandbox Code Playgroud)

当您尝试通过指向成员的指针调用成员函数时,存在差异,因为auto_ptr显然不实现op - >*():

void (MyClass::*memfun)() = &MyClass::foo;

(p->*memfun)();         // OK
(ap->*memfun)();        // Error op->*() missing
(ap.get()->*memfun)();  // OK
Run Code Online (Sandbox Code Playgroud)

为什么auto_ptr中不支持op - >*()以及如何实现它(我已经实验了一段时间,但最终放弃了).

c++ operator-overloading pointer-to-member

17
推荐指数
2
解决办法
321
查看次数

Gtest:未定义的参考文献

我正在尝试使用GoogleTest来测试一个简单的函数,但是当我make在build文件夹中运行时,编译器会Undefined Reference向我抛出错误消息.我引用了gtest头文件,所以我不确定是什么问题.有任何想法吗?我是unix和单元测试的全部主题的新手,所以我很可能会遗漏一些简单的东西.提前致谢!

错误消息:

CMakeFiles/Proj2.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x1e): undefined reference to `testing::InitGoogleTest(int*, char**)'
main.cpp:(.text+0x23): undefined reference to `testing::UnitTest::GetInstance()'
main.cpp:(.text+0x2b): undefined reference to `testing::UnitTest::Run()'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include "gtest/gtest.h"

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
Run Code Online (Sandbox Code Playgroud)

TEST.CPP

#include "gtest/gtest.h"
#include "Testable.h"

TEST(GetTwoTest, Two) {
    EXPECT_EQ(2, GetTwo());
}
Run Code Online (Sandbox Code Playgroud)

Testable.cpp

#include "Testable.h"

int GetTwo() {
    return 3;
}
Run Code Online (Sandbox Code Playgroud)

这是我的CMakeLists.txt文件:

cmake_minimum_required(VERSION 2.6)

SET(CMAKE_CXX_FLAGS "-std=gnu++11") #Turn on C++11 Support

set(FILES_TO_TEST Testable.cpp)
set(UNIT_TESTS …
Run Code Online (Sandbox Code Playgroud)

c++ unix unit-testing cmake googletest

17
推荐指数
1
解决办法
3万
查看次数

使C++类成为监视器(在并发意义上)

我想确保一次只有一个线程可以运行我的C++类的方法.换句话说,让类的行为类似于Monitor.

是否有模式,模板化的方式来做这个,或者我可以使用一些Boost类?因为我到目前为止唯一的想法是添加一个关键部分成员,并在每个方法的开头获取它并在结束时释放它(当然使用RAII).但这似乎非常多余,我不能将它重用于其他类.

c++ concurrency multithreading templates boost

15
推荐指数
2
解决办法
2万
查看次数

为什么在"for-loop"中声明变量的"构造函数方式"允许但在"if-statement"中不允许?

可能重复:
为什么不能用参数构造条件中定义的变量?

考虑这个简单的例子:

/*1*/ int main() {
/*2*/   for (int i(7); i;){break;} 
/*3*/   if (int i(7)) {}
/*4*/ }
Run Code Online (Sandbox Code Playgroud)

为什么line-2编译得很好,而line-3给出错误?这对我来说有点奇怪,为什么if语句在这方面的处理比for-loop更差?

如果这是编译器特定的 - 我用gcc-4.5.1测试:

prog.cpp:在函数'int main()'中:prog.cpp:3:7:错误:在'int'prog.cpp之前的预期primary-expression:3:7:错误:期望')'在'int'之前

我受到了这个问题的启发

[UPDATE]

我知道这个编译得很好:

/*1*/ int main() {
/*2*/   for (int i = 7; i;){break;} 
/*3*/   if (int i = 7) {}
/*4*/ }
Run Code Online (Sandbox Code Playgroud)

[UPDATE2]

这似乎是纯粹的学术问题 - 但对于std::unique_ptr<>无法复制的类型,这可能非常重要:

#include <memory>
int main() {
  if (std::unique_ptr<int> i = new (std::nothrow) int(7)) {
  }
  if (std::unique_ptr<int> i(new (std::nothrow) int(7))) {
  }
} …
Run Code Online (Sandbox Code Playgroud)

c++ for-loop if-statement language-lawyer

15
推荐指数
1
解决办法
615
查看次数

如何在gmock中指定连续返回?

在Mockito中,我们可以指定多个返回值(取自此处):

//you can set different behavior for consecutive method calls.
 //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
 when(mock.someMethod("some arg"))
  .thenReturn(new RuntimeException())
  .thenReturn("foo");

 //There is a shorter way of consecutive stubbing:
 when(mock.someMethod()).thenReturn(1,2,3);
 when(mock.otherMethod()).thenThrow(exc1, exc2);
Run Code Online (Sandbox Code Playgroud)

有没有办法为使用gmock制作的模拟指定多个返回?目前我有:

store_mock_ = std::make_shared<StorageMock>();
ON_CALL(*store_mock_, getFileName(_)).Return("file1").Return("file2");
Run Code Online (Sandbox Code Playgroud)

这不能编译,因为我无法弄清楚gmock中的多个返回.这可能与gmock?如果没有,还有另一种方法可以解决这个问题吗?我发现我们可以EXPECT多次返回值,如:

using ::testing::Return;...
EXPECT_CALL(turtle, GetX())
    .WillOnce(Return(100))
    .WillOnce(Return(200))
    .WillOnce(Return(300));
Run Code Online (Sandbox Code Playgroud)

但是,我没有找到任何模拟多个返回的文档ON_CALL.

c++ googletest mockito googlemock gmock

14
推荐指数
2
解决办法
1万
查看次数

可以在折叠表达式中使用宇宙飞船运算符吗?

试过的编译器都没有接受这样的代码:

template <int ...a> bool foo() { return (a<=> ... <=>0); }

但对于任何其他<=,>=,==,!=,<,>它编译。

cppreference在这里很清楚 -<=>我们可以用于折叠表达式的二元运算符列表中没有。

这是 C++ 标准中的故意遗漏,还是编译器没有准备好?

这个问题只是纯粹的好奇;我只是想知道这方面的 C++ 方向是什么。我可以想象所有其他比较运算符将从允许的运算符的折叠表达式列表中删除,因为它们与<=>折叠表达式一样有意义......

c++ language-lawyer spaceship-operator fold-expression c++20

14
推荐指数
1
解决办法
335
查看次数